import org.objectweb.asm.*;

import java.io.IOException;
import java.util.Arrays;

import static org.objectweb.asm.Opcodes.ASM4;

//测试复制类
public class Copy extends ClassVisitor {
    ClassWriter cw;


    public Copy(ClassWriter cw){
        //传进去一个int 262144;
        super(ASM4);
        this.cw = cw;
    }

    //version代表着java版本
    @Override
    public void visit(int version, int access, String className, String signature, String superName, String[] interfaces){
//        复制
        cw.visit(version,access,className,signature,superName,interfaces);

        System.out.println(version+"|"+access+"|"+className+"|"+signature+"|"+superName+"|"+ Arrays.toString(interfaces));
        System.out.println(className+" extends "+ superName+" {");
    }

    //访问到成员变量时触发事件；descriptor是成员的类型
    @Override
    public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
        cw.visitField(access, name, descriptor, signature, value).visitEnd();

        System.out.println(access+"|"+name+"|"+descriptor+"|"+signature+"|"+value);
        System.out.println("        "+name);
        return super.visitField(access, name, descriptor, signature, value);
    }

    //访问到方法时触发事件；descriptor是方法的返回值
    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        cw.visitMethod(access, name, descriptor, signature, exceptions).visitEnd();

        System.out.println(access+"|"+name+"|"+descriptor+"|"+signature+"|"+exceptions);
        System.out.println("   "+name+"()");
        return super.visitMethod(access, name, descriptor, signature, exceptions);
    }
    //到达class文件尾部，访问结束
    @Override
    public void visitEnd(){
        cw.visitEnd();
        System.out.println("}");
    }


    //重写方法现在回想不就是生命周期原理吗
    public static void main(String[] args) throws IOException {
        ClassWriter cww = new ClassWriter(0);
        //new一个自己，因为自己继承了ClassVisitor，而ClassReader需要ClassVisitor作为参数

        Copy ca = new Copy(cww);

        ClassReader cr = new ClassReader("Stutem");
////        开始解析,第二个参数为何为0不清楚
        cr.accept(ca,0);

//        reader("Stutem");

        //复制好了

        byte[] b = cww.toByteArray();
        MyClassLoader my = new MyClassLoader();
        Class c =  my.defineClass("Stutem",b);




    }

}
